<template>
	<view>
		<view v-if="Object.keys(objData).length">
			<!-- 文章 -->
			<details-article v-if="!code && !isNo && objData.type == 1" :data="objData"></details-article>
			<!-- 视频 -->
			<details-video v-if="!code && !isNo && objData.type == 2" :data="objData" @handlePay="clickPay"></details-video>
			<!-- 非新人首免 -->
			<view
				v-if="!objData.pay_status && !userInfo.user_id && (objData.discount_price * 1) && !objData.is_expires && !(objData.market_ids && objData.market_ids.includes(4) && !userInfo.orders)"
				class="pay-style bg-white">
				<!-- 限时秒杀 -->
				<view
					v-if="objData.type == 1 && !userInfo.is_sale && objData.market_ids && objData.market_ids.includes(5) && objData.marketing_tools[5].status"
					class="Grid Grid--center Grid--justifyCenter text-sm"
					style="position: absolute; bottom: 62px; left: 0; background: rgb(254,240,240); color: #f56c6c; width: 100%; padding: 10px 0;">
					<view style="display: inline-block;">
						<text style="padding: 0 4px; color: #e45656;">限时秒杀</text>
						<u-count-down :time="objData.marketing_tools[5].secs * 1000" format="DD:HH:mm:ss" autoStart
							millisecond @change="onChange" style="display: inline-block;">
							<view class="time">
								<view v-if="timeData.days" class="time__custom">
									<text style="padding: 0 5px;" class="time__custom__item">{{ timeData.days }}天</text>
								</view>
								<view class="time__custom">
									<text
										class="time__custom__item">{{ timeData.hours > 9 ? timeData.hours : '0' + timeData.hours }}</text>
								</view>
								<text class="time__doc">:</text>
								<view class="time__custom">
									<text
										class="time__custom__item">{{ timeData.minutes > 9 ? timeData.minutes : '0' + timeData.minutes }}</text>
								</view>
								<text class="time__doc">:</text>
								<view class="time__custom">
									<text
										class="time__custom__item">{{ timeData.seconds > 9 ? timeData.seconds : '0' + timeData.seconds }}</text>
								</view>
							</view>
						</u-count-down>
						<text
							style="padding: 0 4px; color: #e45656;">剩余{{objData.marketing_tools[5].surplus_show}}份</text>
					</view>
				</view>

				<view class="Media Media--alignCenter  Media--justifyCenter" style="width: 100%;">
					<view class="Media-body" style="color: #E52727;">
						<view class="text-xl">
							<text>￥</text><text style="font-weight: bold;">{{objData.discount_price}}</text>
							<text
								v-if="!userInfo.is_sale && objData.market_ids && objData.market_ids.includes(5) && objData.marketing_tools[5].status"
								class="text-sm"
								style="text-decoration: line-through; color: rgb(153, 153, 153);">&yen;{{objData.price}}</text>
						</view>
						<view v-if="!userInfo.phone_discount && objData.market_ids && objData.market_ids.includes(1)"
							class="text-xs">
							{{objData.discount_fee * 1 ? `绑定手机立减${objData.discount_fee}元` : `绑定手机号码`}}
						</view>
						<view
							v-if="userInfo.phone_discount === 1 && objData.market_ids && objData.market_ids.includes(1)"
							class="text-xs">
							{{objData.discount_fee * 1 ? `享首绑优惠,本单立减${objData.discount_fee}元` : `绑定手机号码`}}
						</view>
					</view>
					<u-button class="bj-color" type="warning" @click="clickPay">立即解锁</u-button>
				</view>

			</view>

			<!-- 新人首免 -->
			<view
				v-if="!objData.pay_status && !userInfo.user_id && !(objData.discount_price * 1) && !objData.is_expires && (objData.market_ids && objData.market_ids.includes(4) && !userInfo.orders)"
				class="pay-style bg-white">
				<view class="Media Media--alignCenter  Media--justifyCenter" style="width: 100%;">
					<u-button style="width: 100%;" class="bj-color" type="warning"
						@click="clickPay">享新人首免，立即免费获取</u-button>
				</view>
			</view>
		</view>

		<!-- 支付方式弹窗 -->
		<pay-popup ref="popup" :price="objData.discount_price * 1" :data="objData" @buyNote="buyNote"
			@confirmPay="confirmPay"></pay-popup>
		<!-- 绑定手机 -->
		<binding-popup ref="bindingPopup" :price="discount_price" :data="objData"
			@confirm="confirmBinding"></binding-popup>
		<!-- 购买须知 -->
		<u-popup :show="show" @close="close" mode="center" :closeOnClickOverlay="false" :safeAreaInsetBottom="false"
			bgColor="transparent">
			<view class="buyHint">
				<view>
					1.本平台仅为内容发布平台，非购彩平台，不提供任何售彩服务。
					<br />
					2.平台虚拟而一经充值成功，只可用于购买平台付费阅读信息服务，不支持提现、退款、转赠流通、兑换、购彩操作。
					<br />
					3.使用本充值服务前，请确认您已年满 18 周岁。若您为未成年人，您使用本服务的行为将被视为已获得监护人认可。
					<br />
					4.专家发布的内容仅代表发布者的个人观点，仅作为交流心得之用，亦不代表平台立场。
				</view>
				<u-button type="primary" :text="`我已知晓`" @click="close"></u-button>
			</view>
		</u-popup>

		<u-overlay v-if="code" show>
			<view class="Grid Grid--center Grid--justifyCenter">
				<image style="width: 200px; height: 200px; margin-top: 20%;" mode="widthFix" :src="code"></image>
			</view>
			<view class="Grid text-base text-center text-white Grid--center Grid--justifyCenter"
				style="padding: 10px 0;">长按识别关注后可查阅</view>
		</u-overlay>
		<!-- 文章已丢失在茫茫宇宙中 -->
		<view v-if="isNo">
			<u-empty mode="page" text="文章已丢失在茫茫宇宙中~" :icon="noPage">
			</u-empty>
		</view>
	</view>
</template>

<script>
	import {
		getDetailsinfo,
		getWzDetailsinfo,
		buyInfo,
		checkPayStatus,
		phoneBind,
		setFocus,
		getApiCode
	} from '@/service/index'
	import {
		mapState,
	} from "vuex";
	import payPopup from '@/components/pay-popup/pay-popup.vue'
	import bindingPopup from '@/components/binding-popup/binding-popup.vue'
	import {
		parseQuery
	} from '@/utils/index.js'
	import {
		sub
	} from "@/utils/bc/bc.js";
	import {
		BASEURL
	} from '@/constant/index.js'
	import noPage from '@/static/images/my/page.png'
	import detailsArticle from './cps/details-article.vue'
	import detailsVideo from './cps/details-video.vue'

	export default {
		data() {
			return {
				show: false, //购买悉知
				objData: {}, //数据信息卸载
				id: null, //方案id
				code: '',
				pay_obj: {},
				discount_price: 0,
				timeData: {},
				isNo: false,
				noPage
			}
		},
		components: {
			payPopup,
			bindingPopup,
			detailsArticle,
			detailsVideo
		},
		computed: {
			...mapState({
				userInfo: state => state.login.userInfo,
				token: state => state.login.token,
				redirect_uri: state => state.login.redirect_uri
			}),
			isObjData() {
				return this.objData.matchInfo && this.objData.matchInfo.competition_info
			}
		},
		async onLoad(options) {
			if (options.key === 'pc' && options.token) {
				// 设置token
				this.$store.commit('login/changeToken', options.token)
				this.$store.commit('login/changeUserInfo', {
					is_sale: 1
				})
			}
			// 更新userinfo
			try {
				await this.$store.dispatch('login/userinfoAction');
				if (Object.keys(this.userInfo).length) {
					if (this.userInfo.is_sale == 1) {
						this.id = options.content_id
						this.getDetails()
					} else {
						this.id = options.content_id
						this.getWzDetails()
					}
				}
				uni.setNavigationBarTitle({
					title: `${this.userInfo.wechat_info.title}`
				})
			} catch (error) {}
		},
		methods: {
			onChange(e) {
				this.timeData = e
			},
			buyNote() {
				this.show = true
			},
			close() {
				this.show = false
			},
			// 用户查看方案信息
			getWzDetails() {
				let params = {
					content_id: this.id,
					appid: this.userInfo.app_id,
				}
				getWzDetailsinfo({
					params
				}).then(res => {
					console.log(res)
					if (res.code == 200) {
						res.data.matchInfo = res.data.match_info
						this.objData = res.data
					}
				}).catch(res => {
					if (res.code == 400) {
						let params = {
							content_id: this.id,
							wechat_id: this.userInfo.wechat_id
						}
						getApiCode(params).then(res => {
							if (res.code == 200) {
								this.code = BASEURL + '/' + res.data.qrcode_url
							}
						})
					}
					if (res.code == 404) {
						this.isNo = true
					}
				})
			},
			// 销售获取详情信息
			getDetails() {
				let params = {
					content_id: this.id
				}
				getDetailsinfo({
					params
				}).then(res => {
					if (res.code == 200) {
						res.data.matchInfo = res.data.match_info ? JSON.parse(res.data.match_info) : ''
						this.objData = res.data
					}
				})
			},
			// 弹窗选择支付方式确认支付
			confirmPay(obj) {
				this.pay_obj = obj
				// 判断是否需要绑定手机
				if (obj.binding && !this.userInfo.phone_discount && this.objData.market_ids.includes(1)) {
					let v = sub(this.objData.discount_price * 1, this.objData.discount_fee * 1)
					// 非新人首免需结合是否用券情况 若有券的情况该couponBinding不为空对象 
					if (!(this.objData.market_ids && this.objData.market_ids.includes(4) && !this.userInfo.orders) &&
						Object.keys(obj.couponBinding).length) {
						v = sub(v, obj.couponBinding.coupon_amount * 1)
					}
					this.discount_price = (v * 1) > 0 ? (v * 1) : 0
					this.$refs.popup.close()
					return this.$refs.bindingPopup.open()
				}
				this.pay(obj)
			},
			// 点击支付弹窗
			clickPay() {
				this.$refs.popup.open()
			},
			// 完成绑定回调
			confirmBinding() {
				this.$refs.bindingPopup.close()
				this.$refs.popup.open()
				this.pay(this.pay_obj)
			},
			pay(obj) {
				if (this.userInfo.cover) {
					// 防封
					const {
						appid
					} = parseQuery()
					let http =
						`${this.redirect_uri}/user/#/pages/pay/pay/?appid=${appid}&content_id=${this.objData.content_id}&sale_id=${this.objData.create_uid}&pay_type=${obj.payType}&coupon_id=${Object.keys(obj.couponBinding).length ? obj.couponBinding.coupon_id : ''}&key=pc&token=${this.token}&redirect_uri=${encodeURIComponent(window.location.origin)}&other=${new Date().getTime()}`
					window.location.href = http
				} else {
					// 常规
					let _this = this
					let params = {
						content_id: this.objData.content_id,
						sale_id: this.objData.create_uid,
						pay_type: obj.payType,
						coupon_id: Object.keys(obj.couponBinding).length ? obj.couponBinding.coupon_id : ''
					}
					uni.showLoading({
						title: '支付中...'
					})
					buyInfo(params).then(resp => {
						if (resp.code == 200) {
							// 判断是否已经支付 注:处理特殊情况,新用户绑定手机享受减免金额大于或等于本单进行的情况
							if (resp.data.order.pay_status) {
								uni.showToast({
									title: '方案已解锁',
									icon: 'none'
								})
								setTimeout(() => {
									window.location.reload()
								}, 500)
								return
							}
							if (obj.payType == 1) {
								WeixinJSBridge.invoke('getBrandWCPayRequest', resp.data.pay_sdk, function(res) {
									if (res.err_msg == "get_brand_wcpay_request:ok") {
										uni.showLoading({
											title: '支付查询中...'
										})
										_this.$refs.popup.close()
										_this.timer = setInterval(function() {
											checkPayStatus({
												order_no: resp.data.order.order_no
											}).then(result => {
												if (result.code == 200) {
													if (result.data.pay_status == 1) {
														window.location.reload()
														clearInterval(_this.timer)
														uni.hideLoading()
													}
												} else {
													clearInterval(_this.timer)
													uni.hideLoading()
												}
											})
										}, 1000);
									} else {
										uni.showToast({
											title: '已取消支付',
											icon: 'none'
										})
										setTimeout(async () => {
											uni.hideLoading()
										}, 1500)
									}
								});
							}
							if (obj.payType == 2) {
								uni.navigateTo({
									url: `/pages/ali_pay/ali_pay?appid=${this.userInfo.appid}&content_id=${this.objData.content_id}&order_no=${resp.data.order.order_no}&token=${this.token}`
								});
							}
						} else {
							uni.hideLoading()
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pay-style {
		padding: 10px 16px;
		display: flex;
		align-items: center;
		display: flex;
		align-items: center;
		position: fixed;
		width: 100%;
		bottom: 0;

		.bj-color {
			width: 106px;
			height: 42px;
			background: linear-gradient(270deg, #E52727 0%, #E52727 100%);
			font-size: 14px;
			color: #FFF0ED;
			line-height: 42px;
			text-align: center;
			border-radius: 800px;
			font-weight: bold;
		}

	}

	.buyHint {
		width: 90%;
		background: #fff;
		margin: auto;
		border-radius: 4px;
		padding: 16px;
		line-height: 22px;

		&>view {
			font-size: 14px;
		}

		&>button {
			width: 100px;
			margin-top: 20px;
		}
	}

	.time {
		@include flex;
		align-items: center;

		&__custom {
			margin-top: 4px;
			// width: 22px;
			// height: 22px;
			// background-color: $u-primary;
			border-radius: 4px;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			justify-content: center;
			align-items: center;

			&__item {
				// color: #fff;
				color: #e45656;
				text-align: center;
			}
		}

		&__doc {
			color: #e45656;
			padding: 0px 4px;
		}

		&__item {
			color: #606266;
			margin-right: 4px;
		}
	}
</style>